/**
 * Description:
 * Class Name:AsyncTest
 * Date:2022/5/28 17:23
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第17章_网络编程._17_6_Java11标准化的HTTPClient._17_6_3_发送异步请求;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class AsyncTest {
    public static void main(String[] args) throws InterruptedException{
        // 为CookieHandler设置默认的Cookie管理器
        CookieHandler.setDefault(new CookieManager());
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .followRedirects(HttpClient.Redirect.NORMAL)
                .connectTimeout(Duration.ofSeconds(20))
                .cookieHandler(CookieHandler.getDefault())
                .build();

        // 创建要被POST发送的request请求体
        HttpRequest postReq = HttpRequest.newBuilder()
                .uri(URI.create("https://www.baidu.com"))
                .timeout(Duration.ofSeconds(20))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString("name=crazyit.org"))
                .build();

        // 创建要被GET发送的request请求体
        HttpRequest getReq = HttpRequest.newBuilder()
                .uri(URI.create("https://www.baidu.com"))
                .timeout(Duration.ofSeconds(20))
                .header("Content-Type", "text/html")
                .GET()
                .build();

        // 可以用 client 发送异步的请求了
        client.sendAsync(postReq, HttpResponse.BodyHandlers.ofString())
                // 当CompletableFuture代表的任务完成时，传入Lambda表达式对该返回值进行转换
                .thenApply(stringHttpResponse -> new Object[]{stringHttpResponse.statusCode(), stringHttpResponse.body()})
                .thenAccept(rt -> {
                    System.out.println("POST请求的响应码：" + rt[0]);
                    System.out.println("POST请求的响应体：" + rt[1]);
                    // 发送异步的GET请求，返回CompletableFuture对象
                    client.sendAsync(getReq, HttpResponse.BodyHandlers.ofString())
                            // 当CompletableFuture代表的任务完成时，传入Lambda表达式对该返回值进行转换
                            .thenAccept(resp -> {
                                System.out.println("GET请求的响应码：" + resp.statusCode());
                                System.out.println("GET请求的响应体：" + resp.body());
                            });
                });
        System.out.println("--程序结束--");
        Thread.sleep(1000);
    }
}
//--程序结束--
//POST请求的响应码：200
//POST请求的响应体：...
//
//GET请求的响应码：200